<?php

namespace App\Http\Controllers\Wechat;

use App\Models\AppInviteCodeBehavior;
use App\Models\BookHomeCollect;
use App\Models\BookHomeOrder;
use App\Models\LibBook;
use App\Models\LibBookBarcode;
use App\Models\BookHomeOrderBook;
use App\Models\BookHomeOrderRefund;
use App\Models\BookHomePostageSet;
use App\Models\BookHomeReturnAddress;
use App\Models\BookHomePostalReturn;
use App\Models\BookHomePurchase;
use App\Models\BookHomePurchaseSet;
use App\Models\BookHomeReturnAddressExplain;
use App\Models\CourierName;
use App\Models\HotSearch;
use App\Models\LibBookRecom;
use App\Models\OtherAccessNum;
use App\Models\Shop;
use App\Models\ShopBook;
use App\Models\UserLibraryInfo;
use App\Validate\BookHomeBorrowValidate;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 图书到家借阅记录
 * Class NewBookBorrow
 * @package app\port\controller
 */
class BookHomeBorrowController extends CommonController
{
    private $validate = null;
    public function __construct()
    {
        parent::__construct();
        $this->validate = new BookHomeBorrowValidate();
    }

    /**
     * 图书到家主界面数据
     */
    public function index()
    {
        $user_id = $this->request->user_info['id'];

        //获取馆藏书推荐
        $libBookRecomModel = new LibBookRecom();
        $lib_book = $libBookRecomModel->lists(['id', 'metaid', 'metatable', 'type_id', 'book_name', 'barcode', 'author', 'press', 'isbn', 'img', 'is_recom', 'create_time'], null, null, null, 1, 6);

        //获取新书上架
        $not_allow_year = BookHomePurchaseSet::where('type', 11)->value('number');
        $shopBookModel = new ShopBook();
        $new_book = $shopBookModel->lists(
            ['n.id', 'type_id', 'n.book_name', 'n.author', 'n.press', 'n.isbn', 'n.img', 'n.intro', 'n.is_recom', 'n.create_time'],
            null,
            null,
            null,
            null,
            2,
            null,
            1,
            null,
            $not_allow_year,
            null,
            2
        );
        if (empty($lib_book['data']) && empty($new_book['data'])) {
            return $this->returnApi(203, '暂无数据');
        }

        if ($lib_book['data']) {
            $data['lib_book']['recom'] = $lib_book['data'] ? $this->disDataSameLevel($lib_book['data'], 'con_type', ['type_name' => 'type_name']) : null;
            //热门馆藏书
            $hot_borrow =  Cache::get('lib_hot_borrow');
            if (empty($hot_borrow)) {
                $hot_borrow = $libBookRecomModel->hotBorrow();
                if ($hot_borrow) {
                    Cache::put('lib_hot_borrow', $hot_borrow, 3600);
                }
            }
            $data['lib_book']['hot_borrow'] = $hot_borrow;
        } else {
            $data['lib_book']['recom'] = null;
            $data['lib_book']['hot_borrow'] = null;
        }


        if ($new_book['data']) {
            foreach ($new_book['data'] as $key => $val) {
                $new_book['data'][$key]['intro'] = str_replace('&nbsp;', '', strip_tags($val['intro']));
            }
            $data['new_book']['new_recom'] = $new_book['data'];

            //热门新书书
            $hot_borrow =  Cache::get('new_hot_borrow');
            if (empty($hot_borrow)) {
                $hot_borrow = $shopBookModel->hotBorrow(3, $not_allow_year);
                if ($hot_borrow) {
                    Cache::put('new_hot_borrow', $hot_borrow, 3600);
                }
            }
            //获取新书热门借阅
            list($data['new_book']['type_name'], $data['new_book']['type_recom']) = $hot_borrow;
        } else {
            $data['new_book']['new_recom'] = null;
            $data['new_book']['type_name'] = null;
            $data['new_book']['type_recom'] = null;
        }

        //获取书袋数量
        //  $data['schoolbag_number'] = BookHomeSchoolbag::where('user_id', $user_id)->count();


        //添加图书到家访问量
        $otherAccessNumModel = new OtherAccessNum();
        $otherAccessNumModel->add(2);


        //增加行为分析
        $appInviteCodeBehaviorModel = new AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(1);

        return $this->returnApi(200, '获取成功', true, $data);
    }


    /**
     * 采购借阅记录
     * @param token ：用户 token
     * @param type  类型 1 申请中  2 借阅中  3 还书中 4 还书成功 5 其他（包括拒绝与已归还的记录）
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function borrowList()
    {
        if (!$this->validate->scene('new_borrow_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];
        $type = $this->request->type;
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;

        //判断读者证号密码是否正确
        // $account_id = '';
        // $account = '';
        //  if (config('other.is_validate_lib_api')) {
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }
        $account_id =  $account_lib_info['id'];
        $account =  $account_lib_info['account'];
        //  }

        switch ($type) {
            case 1:
                $data = $this->applying($user_id, $account_id, $limit);
                break;
            case 2:
                $data = $this->borrowing($user_id, $account_id, $account, $page, $limit);
                break;
            case 3:
                $data = $this->returning($user_id, $account_id, $limit);
                break;
            case 4:
                $data = $this->historyList($user_id, $account_id, $account, $page, $limit);
                break;
            case 5:
                $data = $this->otherList($user_id, $account_id, $limit);
                break;
        }
        if ($data['data']) {
            $LibBook = new LibBook();
            foreach ($data['data'] as $key => $val) {
                if (empty($val['img']) && !empty($val['isbn'])) {
                    $data['data'][$key]['img'] = $LibBook->setImgAttr($val['isbn']);
                }
            }
            return $this->returnApi(200, '获取成功', true, $data['data']);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 获取申请中的记录
     */
    public function applying($user_id, $account_id, $limit)
    {
        $bookHomeOrderBookModel = new BookHomeOrderBook();
        $res = $bookHomeOrderBookModel->from($bookHomeOrderBookModel->getTable() . ' as n')
            ->select('n.id as other_id', 'n.barcode_id', 'n.type', 'n.book_id', 'o.order_number', 'o.is_pay', 'o.change_time', 'o.agree_time')
            ->join('book_home_order as o', 'o.id', '=', 'n.order_id')
            ->where(function ($query) use ($user_id, $account_id) {
                if ($account_id) {
                    $query->where('o.account_id', $account_id);
                } else {
                    $query->where('o.user_id', $user_id);
                }
            })
            ->where(function ($query) {
                $query->Orwhere('is_pay', 2)->Orwhere('is_pay', 6);
            })
            ->orderByDesc('n.id')
            ->paginate($limit)
            ->toArray();

        $shopBookModel = new ShopBook();
        $LibBook = new LibBook();
        foreach ($res['data'] as $key => $val) {
            if ($val['type'] == 1) {
                $obj = $shopBookModel;
                $res['data'][$key]['barcode'] = '';
            } else {
                $obj = $LibBook;
                $res['data'][$key]['barcode'] = LibBookBarcode::where('id', $val['barcode_id'])->value('barcode');
            };
            $book_info = $obj::select('book_name', 'author', 'isbn', 'img', 'press', 'pre_time')->where('id', $val['book_id'])->first();
            if ($book_info) {
                $book_info = $book_info->toArray();
                $res['data'][$key]['book_name'] = $book_info['book_name'];
                $res['data'][$key]['author'] = $book_info['book_name'];
                $res['data'][$key]['isbn'] = $book_info['isbn'];
                $res['data'][$key]['img'] = $book_info['img'];
                $res['data'][$key]['press'] = $book_info['press'];
                $res['data'][$key]['pre_time'] = $book_info['pre_time'];
            } else {
                $res['data'][$key]['book_name'] = '';
                $res['data'][$key]['author'] = '';
                $res['data'][$key]['isbn'] = '';
                $res['data'][$key]['img'] = '';
                $res['data'][$key]['press'] = '';
                $res['data'][$key]['pre_time'] = '';
            }
        }

        return $res;
    }

    /**
     * 获取借阅中的记录
     */
    public function borrowing($user_id, $account_id, $account, $page, $limit)
    {
        $key = md5('borrowing' . $user_id . $account_id . $account . $page . $limit);
        $val = Cache::get($key);
        if ($val) {
            return json_decode($val, true);
        } else {
            if ($account) {
                $libApi = $this->getLibApiObj();
                $res = $libApi->getNowBorrowList($account, $limit);
                if ($res['code'] == 200) {
                    $data = $res['content'];
                } else {
                    $data = [];
                }
            } else {
                $data = [];
            }
            //添加上用户失败的记录
            if ($page == 1) {
                $userLibraryInfoModel = new UserLibraryInfo();
                $result_not_library = $userLibraryInfoModel->getBorrowNotLibrary($user_id, $account_id, true);

                $data = array_merge($data, $result_not_library);
            }

            if ($data) {
                $node['data'] = $data;
            } else {
                $node['data'] = null;
            }
            if (!empty($node['data'])) {
                $node['data'] = sort_arr_by_one_field($node['data'], 'borrow_time', [SORT_STRING, SORT_DESC]);
                Cache::put($key, json_encode($node), 180);
            }
            //去除归还中的数据 暂不处理，有分页等问题
            // $returning_data = $this->returning($user_id, $account_id, 100);
            // if ($returning_data) {
            //     $returning_barcode = array_column($res, 'barcode');
            //     foreach ($node['data'] as $key => $val) {
            //         if($val)
            //     }
            // }
            return $node;
        }
    }

    /**
     * 获取归还中的记录
     */
    public function returning($user_id, $account_id, $limit)
    {
        $postalReturnModel = new BookHomePostalReturn();
        $res = $postalReturnModel
            ->select('id as other_id', 'create_time as early_return_time', 'borrow_time', 'borrow_time as create_time', 'expire_time', 'tracking_number', 'barcode', 'book_name', 'author', 'isbn', 'img', 'press', 'pre_time')
            // ->join("BookHomePurchase u" , 'u.id = p.BookHomePurchase_id')
            ->where(function ($query) use ($user_id, $account_id) {
                if ($account_id) {
                    $query->where('account_id', $account_id);
                } else {
                    $query->where('user_id', $user_id);
                }
            })
            ->where('status', 3)
            ->orderByDesc("id")
            ->paginate($limit)
            ->toArray();

        return $res;
    }
    /**
     * 获取历史的记录
     */
    public function historyList($user_id, $account_id, $account, $page, $limit)
    {
        $key = md5('historyList' . $user_id . $account_id . $account . $page . $limit);
        $val = Cache::get($key);
        if ($val) {
            return json_decode($val, true);
        } else {
            $libApi = $this->getLibApiObj();
            $res = $libApi->getReturnData($account, 150); //固定返回150条
            if ($res['code'] == 200) {
                $data = $res['content'];
            } else {
                $data = [];
            }

            //添加上用户失败的记录
            if ($page == 1) {
                $userLibraryInfoModel = new UserLibraryInfo();
                $result_not_library = $userLibraryInfoModel->getReturnNotLibrary($user_id, $account_id);

                $data = array_merge($data, $result_not_library);
            }

            if ($data) {
                $node['data'] = $data;
            } else {
                $node['data'] = null;
            }

            if (!empty($node['data'])) {
                $node['data'] = sort_arr_by_one_field($node['data'], 'borrow_time', [SORT_STRING, SORT_DESC]);
                Cache::put($key, json_encode($node), 180);
            }
            return $node;
        }
    }
    /**
     * 其他记录（用户手动拒绝或无法发货的记录）
     */
    public function otherList($user_id, $account_id, $limit)
    {
        $bookHomeOrderBookModel = new BookHomeOrderBook();
        $res = $bookHomeOrderBookModel->from($bookHomeOrderBookModel->getTable() . ' as n')
            ->select('n.id as other_id', 'n.barcode_id', 'n.type', 'n.book_id', 'o.change_time', 'o.refund_remark', 'o.refund_time', 'o.is_pay', 'o.agree_time', 'o.deliver_time', 'o.cancel_time', 'o.cancel_remark', 'o.id')
            ->join('book_home_order as o', 'o.id', '=', 'n.order_id')
            ->where(function ($query) use ($user_id, $account_id) {
                if ($account_id) {
                    $query->where('o.account_id', $account_id);
                } else {
                    $query->where('o.user_id', $user_id);
                }
            })
            ->where(function ($query) {
                $query->Orwhere('is_pay', 5)->Orwhere('is_pay', 7)->Orwhere('is_pay', 9)->Orwhere('is_pay', 10);
            })
            ->paginate($limit)
            ->toArray();

        $shopBookModel = new ShopBook();
        $LibBook = new LibBook();
        foreach ($res['data'] as $key => $val) {
            if ($val['type'] == 1) {
                $obj = $shopBookModel;
                $val['barcode'] = '';
            } else {
                $obj = $LibBook;
                $val['barcode'] = LibBookBarcode::where('id', $val['barcode_id'])->value('barcode');
            };
            $book_info = $obj::select('book_name', 'author', 'isbn', 'img', 'press', 'pre_time')->where('id', $val['book_id'])->first()->toArray();
            $res['data'][$key] = array_merge($val, $book_info);
        }
        return $res;
    }


    /**
     * 图书馆设置的运费详情(书店及图书馆)
     * @param  $type 1 新书（默认）  2 馆藏书
     */
    public function postageList()
    {
        // 自动验证
        if (!$this->validate->scene('postage_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $data = BookHomePostageSet::select('number', 'price')->where('type', $this->request->type)->get()->toArray();
        if (!empty($data)) {
            return $this->returnApi(200, '获取成功', true, $data);
        }
        return $this->returnApi(203, '邮费获取失败,请联系管理员');
    }

    /**
     * 检索热词列表
     * @param type  1 新书（默认）  2 馆藏书
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function hotSearchList()
    {
        if (!$this->validate->scene('hot_search_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $type = intval($this->request->input('type', 1)) ?: 1;
        $page = intval($this->request->input('page', 1)) ?: 1;
        $limit = intval($this->request->input('limit', 10)) ?: 10;

        $res = HotSearch::select('content')
            ->where('type', $type)
            ->orderByDesc('number')
            ->paginate($limit)
            ->toArray();

        if ($res['data']) {
            //增加排名
            foreach ($res['data'] as $key => $val) {
                $res['data'][$key]['rank'] = ($page - 1) * $limit + $key + 1;
            }

            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 线上邮递书籍归还（获取当前借阅记录 ，包括新书或馆藏书）
     * @param token ：用户 token
     */
    public function getNowBorrowList()
    {
        $user_id = $this->request->user_info['id'];

        //判断读者证号密码是否正确
        //  $account_id = '';
        //  $account = '';
        //  if (config('other.is_validate_lib_api')) {
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }
        $account_id = $account_lib_info['account_id'];
        $account = $account_lib_info['account'];
        // }

        //获取邮递信息
        // $lib_postal_address = BookHomeReturnAddress::select('username', 'tel', 'province', 'city', 'district', 'street', 'address')
        //     ->where('type', 1)
        //     ->first();

        //获取馆藏书当前借阅信息
        $libApi = $this->getLibApiObj();
        $res = $libApi->getNowBorrowList($account, 1, 100);
        //  $BookHomePurchase = new BookHomePurchaseModel();
        // $return_data = $BookHomePurchase->getReturnIng($account_lib_info['id']); //除去正在归还中的数据
        $return_data = BookHomePostalReturn::where('status', 3)
            ->where(function ($query) use ($user_id, $account_id) {
                if ($account_id) {
                    $query->where('account_id', $account_id);
                } else {
                    $query->where('user_id', $user_id);
                }
            })->pluck('barcode')
            ->toArray(); //除去正在归还中的数据

        if ($res['code'] == 200) {
            foreach ($res['content'] as $key => $val) {
                //查询此书是否是新书
                $shop_id = BookHomePurchase::where('barcode', $val['barcode'])
                    ->where(function ($query) use ($user_id, $account_id) {
                        if ($account_id) {
                            $query->where('account_id', $account_id);
                        } else {
                            $query->where('user_id', $user_id);
                        }
                    })
                    ->orderByDesc('id')
                    ->value('shop_id');
                if ($shop_id) {
                    $res['content'][$key]['shop_id'] = $shop_id;
                    $res['content'][$key]['shop_name'] = Shop::where('id', $shop_id)->value('name');
                } else {
                    $res['content'][$key]['shop_id'] = null;
                    $res['content'][$key]['shop_name'] = null;
                }

                if (!empty($return_data)) {
                    if (!in_array($val['barcode'], $return_data)) {
                        //$data[] = $val;
                        $res['content'][$key]['return_state'] = 1;
                    } else {
                        $res['content'][$key]['return_state'] = 3;
                    }
                } else {
                    $res['content'][$key]['return_state'] = 1;
                }
            }
        } else {
            $res['content'] = [];
        }
        //添加上用户失败的记录
        $userLibraryInfoModel = new UserLibraryInfo();
        $result = $userLibraryInfoModel->getBorrowNotLibrary($user_id, $account_id, false);

        $data = array_merge($res['content'], $result);

        // $lib_postal_address['address_info'] = $lib_postal_address['province'] . $lib_postal_address['city'] . $lib_postal_address['district'] . $lib_postal_address['street'] . $lib_postal_address['address'];
        // $info['lib_postal_address'] = $lib_postal_address;
        if ($data) {
            $info['borrow_info'] = $data;
            return $this->returnApi(200, '获取成功', true, $info);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 获取快递公司名称
     * @param content 检索
     */
    public function getCourierName()
    {
        $content = $this->request->input('content');
        $res = CourierName::select('id', 'name')
            ->where(function ($query) use ($content) {
                if (!empty($content)) {
                    $query->where('name', 'like', "%$content%");
                }
            })->get()
            ->toArray();
        if ($res) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(202, '暂无数据');
    }

    /**
     * 书籍归还提交(包括新书和馆藏书)
     * @param token ：用户 token
     * @param courier_id 快递公司名称id
     * @param barcodes 条形码  多个 逗号  拼接
     * @param tracking_number 快递单号   8 到 18位 之间
     */
    public function recomReturn()
    {
        if (!$this->validate->scene('recom_return')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $courier_id = $this->request->input('courier_id', 35);
        $barcodes = $this->request->barcodes;
        $user_id = $this->request->user_info['id'];
        $tracking_number = $this->request->tracking_number;
        $barcodes = explode(',', $barcodes);
        if (empty(trim($tracking_number)) || letter_or_number($tracking_number) !== true) {
            return $this->returnApi(203, '快递单号规则不正确');
        }

        $bookHomePurchaseModel = new BookHomePurchase();
        //判断读者证号密码是否正确
        $userLibraryInfoModel = new UserLibraryInfo();
        $account_lib_info = $userLibraryInfoModel->checkAccountPwdIsNormal($user_id);
        if (is_string($account_lib_info)) {
            return $this->returnApi(204, $account_lib_info);
        }
        $account_id = $account_lib_info['account_id'];
        $account = $account_lib_info['account'];

        $lib_result = [];
        if (config('other.is_validate_lib_api')) {
            //获取用户所有借阅信息
            $libApi = $this->getLibApiObj();
            $lib_results = $libApi->getNowBorrowList($account, 1, 100);
            if ($lib_results['code'] != 200) {
                $lib_result = [];
            } else {
                $lib_result = $lib_results['content'];
            }
        }

        //添加上用户失败的记录
        $userLibraryInfoModel = new UserLibraryInfo();
        $local_result = $userLibraryInfoModel->getBorrowNotLibrary($user_id, $account_id, false);
        $result = array_merge($lib_result, $local_result);
        if (empty($result)) {
            return $this->returnApi(202, '暂无数据');
        }

        DB::beginTransaction();
        try {
            //判断书籍是否符合归还要求
            $bookHomePurchaseModel->checkIsExceed($barcodes, $user_id, $account_id);

            $purchase_ids = [];
            $where = [];
            foreach ($barcodes as $key => $val) {
                if (config('other.is_validate_lib_api')) {
                    $res = $libApi->validateReturn($val);
                    if ($res['code'] != 200) {
                        throw new \Exception($res['msg']);
                    }
                }
                foreach ($result as $k => $v) {
                    if ($v['barcode'] == $val) {
                        $where[$key]['courier_id'] = $courier_id;
                        $where[$key]['tracking_number'] = $tracking_number;
                        $where[$key]['user_id'] = $user_id;
                        $where[$key]['account_id'] = $account_id;
                        $where[$key]['barcode'] = $v['barcode'];
                        $where[$key]['book_name'] = $v['book_name'];
                        $where[$key]['author'] = $v['author'];
                        $where[$key]['price'] = $v['price'];
                        $where[$key]['book_num'] = $v['book_num'];
                        $where[$key]['isbn'] = $v['isbn'];
                        $where[$key]['press'] = $v['press'];
                        $where[$key]['pre_time'] = $v['pre_time'];
                        $where[$key]['borrow_time'] = $v['borrow_time'];
                        $where[$key]['expire_time'] = $v['expire_time'];
                        $where[$key]['create_time'] = date('Y-m-d H:i:s');

                        $purchase_id = $bookHomePurchaseModel->where('barcode', $v['barcode'])
                            ->where(function ($query) use ($user_id, $account_id) {
                                if ($account_id) {
                                    $query->where('account_id', $account_id);
                                } else {
                                    $query->where('user_id', $user_id);
                                }
                            })
                            ->where('return_state', 1)
                            ->value('id');
                        if (!empty($purchase_id)) {
                            $where[$key]['purchase_id'] = $purchase_id;
                            $purchase_ids[] = $purchase_id;
                        } else {
                            $where[$key]['purchase_id'] = 0;
                        }
                    }
                }
            }
            $postalReturnModel = new BookHomePostalReturn();
            $postalReturnModel->insert($where);

            //修改采购书籍记录
            if (!empty($purchase_ids)) {
                $bookHomePurchaseModel->whereIn('id', $purchase_ids)->update([
                    'return_time' => date('Y-m-d H:i:s'),
                    'return_state' => 3,
                ]);
            }
            //添加系统消息
            $this->systemAdd('邮递还书：提交成功', $user_id, $account_id, 62, null, '邮递还书提交成功，等待后台管理员处理');

            DB::commit();
            return $this->returnApi(200, '提交成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
    /**
     * 图书到家归还地址管理
     */
    public function returnAddress()
    {
        //归还方式说明
        $bookHomeReturnAddressExplainModel = new BookHomeReturnAddressExplain();
        $addressExplain = $bookHomeReturnAddressExplainModel->addressExplain();
        $data['address_explain'] = $addressExplain;
        //获取归还地址
        $bookHomeReturnAddressModel = new BookHomeReturnAddress();
        $addressList = $bookHomeReturnAddressModel->addressList();
        $data['address_list'] = $addressList;

        return $this->returnApi(200, '获取成功', true, $data);
    }

    /**
     * 用户撤销线上书籍归还记录
     * @param token  用户token
     * @param return_id  邮递归还id
     */
    public function bookCancel()
    {
        if (!$this->validate->scene('cancel_return')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $postal_info = BookHomePostalReturn::find($this->request->return_id);
        if (empty($postal_info) || $postal_info['status'] != 3) {
            return $this->returnApi(202, '网络错误');
        }
        $bookHomePurchaseModel = new BookHomePurchase();
        if (isset($postal_info->purchase_id)) {
            $purchase_info = $bookHomePurchaseModel->find($postal_info->purchase_id);
            if (empty($purchase_info) || $purchase_info['return_state'] != 3) {
                return $this->returnApi(202, '网络错误');
            }
        }

        DB::beginTransaction();
        try {
            //修改状态
            $postal_info->change_time = date('Y-m-d H:i:s');
            $postal_info->status = 4;
            // $postal_info->return_manage_id = self::$param['user_id'];
            $postal_info->save();

            if (isset($postal_info->purchase_id)) {
                $purchase_info->return_state = 1;
                $purchase_info->return_time = null;
                $purchase_info->save();
            }

            DB::commit();
            return $this->returnApi(200, '撤销归还成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '撤销失败');
        }
    }

    /**
     * 新书与馆藏书收藏与取消收藏
     * @param  token ：用户 token
     * @param  $type 1 新书（默认）  2 馆藏书
     * @param  $book_id 书籍id
     */
    public function bookCollect()
    {
        // 自动验证
        if (!$this->validate->scene('new_book_collect')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $type = $this->request->type;
        $book_id = $this->request->book_id;
        $user_id = $this->request->user_info['id'];
        if (empty($book_id)) {
            return $this->returnApi(201, '此书不能加入收藏');
        }

        $res = BookHomeCollect::isCollect($book_id, $user_id, $type);
        if (empty($res)) {
            $bookCollectModel = new BookHomeCollect();
            $result = $bookCollectModel->add([
                'user_id' => $user_id,
                'book_id' => $book_id,
                'type' => $type,
            ]);
            $msg = '收藏';
        } else {
            $result = $res->delete();
            $msg = '取消收藏';
        }
        if ($result) {
            return $this->returnApi(200, $msg . '成功', true);
        }
        return $this->returnApi(202, $msg . '失败');
    }

    /**
     * 取消图书到家订单
     * @param order_id 订单id
     * @param cancel_remark 取消备注
     */
    public function cancelBookHomeOrder()
    {
        // 自动验证
        if (!$this->validate->scene('cancel_book_home_order')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $bookHomeOrderModel = new BookHomeOrder();
        $res = $bookHomeOrderModel
            ->select('id', 'is_pay', 'payment', 'type')
            ->where('id', $this->request->order_id)
            ->first();
        if (empty($res)) {
            return $this->returnApi(202, '订单不存在');
        }
        if ($res['is_pay'] != 2) {
            return $this->returnApi(202, '此状态无法取消订单，无有问题请联系管理员');
        }

        //退款成功
        DB::beginTransaction();
        try {
            $res->is_pay = 10; //已取消
            $res->cancel_time = date('Y-m-d H:i:s');
            $res->cancel_remark = $this->request->cancel_remark;
            $res->save();

            if ($res['payment'] == 1) {
                $bookHomeOrderRefundModel = new BookHomeOrderRefund();
                $bookHomeOrderRefundModel->refund($this->request->order_id, $this->request->cancel_remark);
            }

            //馆藏书不处理
            if ($res->type == 1) {
                $bookHomeOrderBookModel = new BookHomeOrderBook();
                $book_id_all = $bookHomeOrderBookModel->where('order_id', $this->request->order_id)->pluck('book_id');
                //增加库存
                foreach ($book_id_all as $v) {
                    $shopBookModel = new ShopBook();
                    $res = $shopBookModel::modifyRepertoryNumber($v, 1);
                    if ($res !== true) {
                        throw new \Exception($res);
                    }
                }
            }

            DB::commit();
            return $this->returnApi(200, '取消成功', true);
        } catch (\Exception $e) {
            Log::error('图书到家退款失败：' . $e->getMessage() . $e->getFile() . $e->getLine());

            DB::rollBack();
            return $this->returnApi(202, '取消失败');
        }
    }
}
